package com.zenghus.spring.formework.aop;

import java.lang.reflect.Field;
import java.lang.reflect.Proxy;

/**
 * @author zenghu
 * @date 2018/5/6 15:39
 */
public class AopProxyUtils {

    public static Object get(Object proxy) throws Exception{
        //先判断传进来的对象是否是代理过的对象

        //如果不是代理对象直接返回
        if(!isAopProxy(proxy)){return proxy; }

        return getProxyTargetObject(proxy);
    }

    private static boolean isAopProxy(Object object){
        return Proxy.isProxyClass(object.getClass());
    }

    private static Object getProxyTargetObject(Object proxy) throws Exception{
        Field h= proxy.getClass().getSuperclass().getDeclaredField("h");
        h.setAccessible(true);
        AopProxy aopProxy= (AopProxy) h.get(proxy);
        Field target=aopProxy.getClass().getDeclaredField("target");
        target.setAccessible(true);
        return target.get(aopProxy);
    }


}
